require('./index.scss');
var Config = require('common/config');
var Tool = require('common/tool');
require('comp/tab');
require('comp/dialog');
var page ;

var vm = avalon.define({
    $id: 'transfer',
    lang: _language=='zh' ? 'CN':'TW',
    step:1, 
    queryLoad:false,
    submitLoad:false,
    user:'',
    from:'',                //转出账号
    to:'',                  //转入账号
    rateMap:'',
    amount:'',              // 转账金额
    activity:'',            // 活动
    accoutShecmeList:'',    // 活动列表
    transoutExchangedRate:'',
    accTradeInfoList:'',
    selectFrom:{
        show:false,
    },
    $computed:{
        rate: function(){
            // 汇率
            return this.rateMap[this.from.currency + this.to.currency];
        },
        transoutAmount: function(){
            // 转出金额 (转出金额=转账金额 * 转账币种_转出币种的汇率)
            var rate = this.rateMap[this.from.currency + this.to.currency]; 
            return (this.amount * 1 * rate).toFixed(2);
        },
        transinAmount: function(){
            // 转入金额 (转入金额=系统汇率 *转账金额)
            var rate = this.rateMap[this.from.currency + this.to.currency],
                amount = this.amount.replace(/\D+/g,''),
                caculate = amount ? amount * 1 * rate : 0;
            return caculate.toFixed(2);
        }
    },
    // 活动记录弹窗
    acRecordDialog:{
        display:"none",
        title: '活动记录',
        thList:[
            {label:'活动名称', text:"eventName"},
            {label:'活动内容', text:"displayName"},
            {label:'记录状态', text:"displayNameCn"},
            {label:'先赠赠金', className:"primary", text:function(el){
                var currencyStr = vm.activity.currency=='USD' ? '$' : '￥';
                return currencyStr + el['givenBonus'];
            }},
            {label:'已释放赠金', className:"primary", text:function(el){
                var currencyStr = vm.activity.currency=='USD' ? '$' : '￥';
                return currencyStr + el['releasedBonus'];
            }},
            {label:'将扣除赠金', className:"primary", text:function(el){
                var currencyStr = vm.activity.currency=='USD' ? '$' : '￥';
                return currencyStr + el['bonusOutAmount'];
            }}
        ],
        list:'',
    },
    /* 限制金额只能输入数字 */
    transAmountInput:function(e){
        console.log(e.target.value);
        var str = e.target.value.replace(/\D+/g,'');
        e.target.value = str;
    },
    /* 转入转出兑换 */
    switchFromTo:function(){
        var from = this.from;
        this.from = this.to;
        this.to = from;
    },
   /* 切换转出账号 */
   switchFrom:function(el, index){
        var toIndex = index===0 ? 1:0;
        if(el.platformName != this.from.platformName){
            this.from = el;
            this.to = this.accTradeInfoList[toIndex];
        }
        this.selectFrom.show = false;
   },
   /* 刷新余额 */
   refresh:function() {
       page.refreshAmount();
    },
    submitfn:function(){
        var amount = vm.amount.trim();
        if( amount=='' || isNaN(amount) ){
            layer.alert('请输入取款金额');
            return false;
        }
        page.checkTransfer();
   },
   confirmSubmit:function(){
        page.confirmSubmit();

   }
});

vm.$watch('onReady',function(){
    page = new PageModel();
    window['vm'] = vm;
});

//入账金额 =  系统汇率*(取款金额-手续费)
function caculate_payAmount(){
    var _caculation = vm.rate * (Number(vm.transAmount) - vm.feeInfo.totalFee );
    vm.feeInfo.payAmount = _caculation.toFixed(2);
}

function PageModel(){
    this.queryInfo();
    
}

// 获取取款页面信息
PageModel.prototype.queryInfo = function(){
    var that = this;
    vm.queryLoad = true;
    Tool.ajax({
        url: '/fundTransfer',
        type:"post"
    }).done(function(res){
        vm.queryLoad = false;

        var data = res.data,
            accTradeInfoList = data.userList.accTradeInfoList;
        if( accTradeInfoList.length===1 ){
            layer.alert('您只有一个操作，无法操作转账', function(){
                stateman.go('home');
            });
            return false;
        }
        vm.user = data.userList;
        vm.rateMap = data.rateMap;
        vm.accTradeInfoList = accTradeInfoList;
        vm.from = accTradeInfoList[0];
        vm.to = accTradeInfoList[1];
        page.queryActivity();
    });
}

// 刷新可用余额
PageModel.prototype.refreshAmount = function(){
    var loading = layer.load(2,{shade:[.3, '#000']});
    Tool.ajax({
        url: '/getAdvisableCredit',
        data:{
            gts2AccountId:vm.from.gts2AccountId
        },
        type:"post"
    }).done(function(res){
        layer.close(loading);
        var data = res.data;
        vm.from.withdrawableAmount = data.advisableCredit;
    });
}

// 取款，转账，升降级活动参加赠金活动接口
PageModel.prototype.queryActivity = function(){
    var that = this;
    Tool.ajax({
        url: '/shecmRecode',
        data:{
            gts2AccountId: vm.from.gts2AccountId,
            operType: 'pc',
            category: 'transfer',
        },
        type:"post"
    }).done(function(res){
        var data = res.data;
        vm.activity = data;
        if(data.accoutShecmeList.length>0){
            data.accoutShecmeList.unshift({
                displayName:"",
                eventName:"",
                displayNameCn:"",
                givenBonus:data.sumGivenBonus,
                bonusOutAmount:data.sumBonusOutAmount,
                releasedBonus:data.sumReleasedBonus,
            });
        }
        vm.acRecordDialog.list = data.accoutShecmeList;
    });
}

/* 获取提交参数 */
function querySubmitParams(){
    var from = vm.from,
        to = vm.to;
    var _params = {
            transoutGts2AccountId: from.gts2AccountId,
            transoutGts2CustomerId: from.gts2CustomerId,
            transoutAccountNo: from.accountNo,
            transoutAmount: vm.transoutAmount,
            transoutCurrency: from.currency,
            transoutPlatform: from.platform,
            transferAmount: vm.amount,
            transinGts2AccountId: to.gts2AccountId,
            transinGts2CustomerId: to.gts2CustomerId,
            transinAccountNo: to.accountNo,
            transinAmount: vm.transinAmount,
            transinCurrency: to.currency,
            transinExchangedRate: vm.rate,
            transinPlatform: to.platform,
        };
    return _params;
}

// 转账数据验证
PageModel.prototype.checkTransfer = function(_valid){
    var that = this;
    if( !vm.activity ){
        layer.alert('正在检测是否存在取款活动，请5s后再提交。');
        return false;
    }
    if( vm.submitLoad )  return;
    vm.submitLoad = true;

    var _params = querySubmitParams();
    
    if( _valid ) _params.valid = _valid;
    Tool.ajax({
        url: '/fundTransferValidate',
        data:_params,
        type:"post"
    }).done(function(res){
        vm.submitLoad = false;
        var data = res.data;
        if( data.recode ){
            var str = '若您申请转账，则'+vm.activity.accoutShecmeList.length;
            str +='个活动资格将会被取消，同时已赠送的金额（'+vm.activity.sumBonusOutAmount+vm.activity.currenyName;
            str +='）将从账户中扣除。您确定要继续转账吗？';
            layer.confirm(str,function(index){
                that.checkTransfer(true);
                layer.close(index);
            });
        }else{
            vm.step=2;
        }
    });
}

// 确认转账
PageModel.prototype.confirmSubmit = function(){
    if( vm.submitLoad )  return;
    vm.submitLoad = true;

    var from = vm.from,
        to = vm.to;
    var _params = querySubmitParams();
    Tool.ajax({
        url: '/fundTransferSubmit',
        data:_params,
        type:"post"
    }).done(function(res){
        vm.submitLoad = false;

        var data = res.data;
        var msg = '<p>转账成功！</p>';
            msg += '<p>转入金额：'+vm.amount+to.currency+'</p>';

        layer.open({
            title: '成功',
            closeBtn:false,
            content: msg,
            yes:function(index){
                location.reload();
                layer.close(index);
                layer.load(1);
            }
        }); 
    });
}




